package top.mccat.filesystem.utils.io;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import top.mccat.filesystem.bean.MyFile;
import top.mccat.filesystem.exception.FileDownloadException;
import top.mccat.filesystem.exception.FileSizeExceedException;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author JMY
 * @Description TODO
 * @Version 1.0.0
 * @Date 2023/2/21 16:58
 * @Created by JMY
 */
@Component
@Slf4j
public class FileUtils {

    @Value("${file.profile}")
    private String profile;

    private final byte[] buffer = new byte[1024 * 8];

    public void uploadFile(MultipartFile file) throws IOException {
        //获取文件名
        String fileName = file.getOriginalFilename();
        //设置文件存储路径
        String path = profile+"/"+fileName;
        File dest = new File(path);
        //检测是否存在该目录
        if (!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        //写入文件
        file.transferTo(dest);
    }

    public void downloadFile(MyFile file, HttpServletResponse response) throws IOException{
        File localFile = new File(profile+"/"+file.getFileName());
        if(!localFile.exists()){
            throw new FileNotFoundException("本地文件["+file.getFileName()+"]未找到");
        }
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/force-download");
        //设置文件名
        response.setHeader("Content-Disposition", localFile.getName());
        //允许访问其他头
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        OutputStream os = response.getOutputStream();
        FileInputStream fis = new FileInputStream(localFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        try{
            int i = bis.read(buffer);
            while (i != -1){
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }catch (IOException e){
            e.printStackTrace();
            throw new FileDownloadException("文件下载错误，下载io问题，请联系开发人员");
        }finally {
            try {
                bis.close();
                fis.close();
                os.close();
            }catch (IOException e){
                e.printStackTrace();
                log.debug("流关闭失败");
            }
        }
    }

    public void deleteFile(MyFile file) throws FileNotFoundException {
        File localFile = new File(profile+"/"+file.getFileName());
        if(localFile.exists()){
            localFile.delete();
        }else {
            throw new FileNotFoundException("本地文件["+file.getFileName()+"]未找到");
        }
    }

    public ResponseEntity<byte[]> getPreviewFile(MyFile myFile){
        return null;
    }
}
